//
//  B_MineViewController.m
//  Application
//
//  Created by 薛小刚 on 2018/8/8.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_MineViewController.h"
#import "B_SettingViewController.h"
#import "B_RealNameViewController.h"
#import "B_MyWalletViewController.h"
#import "B_ApplyBusinessVC.h"
#import "B_MyMessageViewController.h"
#import "B_SweepViewController.h"
#import "B_CollectionViewController.h"
#import "B_AttentionViewController.h"
#import "B_FansViewController.h"
#import "B_FooterPrintViewController.h"
#import "B_MyTopicListVC.h"
#import "B_MyActivityListVC.h"
#import "B_IntegralViewController.h"
#import "B_UserOrderManagerVC.h"
#import "B_UserBasicModel.h"



#import "B_MineHeaderView.h"
#import "B_MineFooterView.h"
#import "B_MineHeaderMoreView.h"
#import "B_MineTopicTVC.h"
#import "B_MineActivityTVC.h"
/// 支付结果  测试
#import "B_PayResultViewController.h"
#import "B_CommentListVC.h"


#import "B_ListCenterAlertView.h"
#import "B_ImageAlertView.h"



#import "AddressPickerView.h"
#import "XGDatePicker.h"

/// 商家订单  测试的
#import "B_MerchantOrderVC.h"


@interface B_MineViewController ()

@property (nonatomic, assign) BOOL animation;

@property (nonatomic, strong) BaseTableView * mainView;
/// 用户的基本信息的模型
@property (nonatomic, strong) B_UserBasicModel * userModel;
/// 存储右侧按钮的cellModel
@property (nonatomic, strong) NSMutableArray * dataSource;
/// 存放用户的图片
@property (nonatomic, strong) NSMutableArray * imageArray;


@end

@implementation B_MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _animation = NO;
    _imageArray = [NSMutableArray array];
    self.view = self.mainView;
    WeakSelf(weSelf, self);
    [self setRightImageBarButtonItemWithFrame:CGRectZero image:@"B_topic_details_more" selectImage:@"" ishidden:YES action:^(GUIButton *button) {
        /// TODO:执行右侧点击事件
        if (weSelf.dataSource) {
            B_ListCenterAlertView * view = [B_ListCenterAlertView initB_ListCenterAlertView];
            [view show];
            if (weSelf.dataArray.count == 0) {
                for (B_CellModel * model in weSelf.dataSource) {
                    [weSelf.dataArray addObject:model.title];
                }
            }
            view.dataArray = weSelf.dataArray;
            view.selectIndex = ^(NSIndexPath *indexPath) {
                
                B_CellModel * cellmodel = weSelf.dataSource[indexPath.row];
                if ([cellmodel.title isEqualToString:@"实名认证"]) {
                    if ([weSelf.userModel.userState isEqualToString:@"1"]) {
                        [KeyWindow makeToast:@"请耐心等待,您提交的信息正在排队!"];
                        return ;
                    } else if ([weSelf.userModel.userState isEqualToString:@"2"]) {
                        [KeyWindow makeToast:@"您提交的信息审核成功, 可以进行实名商家认证!"];
                        return ;
                        
                    } else if ([weSelf.userModel.userState isEqualToString:@"3"]) {
                        BaseViewController * controller = [[NSClassFromString(cellmodel.viewController) alloc] init];
                        [weSelf pushNextViewController:controller];
                        
                    } else if ([weSelf.userModel.userState isEqualToString:@"4"]) {
                        BaseViewController * controller = [[NSClassFromString(cellmodel.viewController) alloc] init];
                        [weSelf pushNextViewController:controller];
                        
                    }
                } else if ([cellmodel.title isEqualToString:@"申请商家"]) {
                    if ([weSelf.userModel.userState isEqualToString:@"1"]) {
                        [KeyWindow makeToast:@"请耐心等待, 您还未通过实名认证!"];
                        return ;
                    } else if ([weSelf.userModel.userState isEqualToString:@"2"]) {
                        if ([weSelf.userModel.businessState isEqualToString:@"1"]) {
                            [KeyWindow makeToast:@"请耐心等待,您提交的信息正在等待审核!"];
                            return ;
                        } else if ([weSelf.userModel.businessState isEqualToString:@"2"]) {
                            [weSelf alertViewCenterWithTitle:@"恭喜您" message:@"你提交的申请已经通过审核!" buttonsTitles:@[@"关闭"] action:^(NSInteger index) {
                                [weSelf getData];
                            }];
                        } else if ([weSelf.userModel.businessState isEqualToString:@"3"]) {
                            BaseViewController * controller = [[NSClassFromString(cellmodel.viewController) alloc] init];
                            [weSelf pushNextViewController:controller];
                            
                        } else if ([weSelf.userModel.businessState isEqualToString:@"4"]) {
                            BaseViewController * controller = [[NSClassFromString(cellmodel.viewController) alloc] init];
                            [weSelf pushNextViewController:controller];
                        }
                    } else if ([weSelf.userModel.userState isEqualToString:@"3"]) {
                        [KeyWindow makeToast:@"您的实名认证申请失败了, 请重新填写!"];
                        return ;
                        
                    } else if ([weSelf.userModel.userState isEqualToString:@"4"]) {
                        [KeyWindow makeToast:@"您还未进行实名认证, 暂时还不可以申请商家!"];
                        return ;
                        
                    }
                    
                } else {
                    BaseViewController * controller = [[NSClassFromString(cellmodel.viewController) alloc] init];
                    [weSelf pushNextViewController:controller];
                }
            };
        }
    }];
    
    
}

- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        [_mainView setTableViewFrameWithTop:-getNavHeight() left:0 right:0 bottom:0];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_MineTopicTVC" bundle:nil] forCellReuseIdentifier:@"B_MineTopicTVC"];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_MineActivityTVC" bundle:nil] forCellReuseIdentifier:@"B_MineActivityTVC"];
        /// 组数
        _mainView.numberOfSectionsBlock = ^NSInteger(UITableView *tableView) {
            return 3;
        };
        /// cell数
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                return 0;
            } else {
                return 1;
            }
        };
        /// 组头的高度
        _mainView.heightForHeaderBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                return 340;
            } else {
                return 50;
            }
        };
        /// 组头
        _mainView.viewForHeaderBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                B_MineHeaderView * header0 = [B_MineHeaderView initB_MineHeaderView];
                header0.B_userName.text = safeValue0(weSelf.userModel.nickName);
                header0.B_userSignature.text = safeValue0(weSelf.userModel.signature);
                NSString * sex = @"", * city = @"城市未填写";
                if ([weSelf.userModel.sex isEqualToString:@"1"]) {
                    sex = @"男";
                } else if ([weSelf.userModel.sex isEqualToString:@"2"]) {
                    sex = @"女";
                } else {
                    sex = @"性别未填写";
                }
                header0.B_sexLabel.text = sex;
                header0.B_ageLabel.text = [NSString stringWithFormat:@"%@ 岁", safeValue1(weSelf.userModel.age)];
                if (ISNULL(weSelf.userModel.city)) {
                    
                } else {
                    city = [NSString stringWithFormat:@"%@ %@ %@", weSelf.userModel.province, weSelf.userModel.city, weSelf.userModel.district];
                }
                header0.B_cityLabel.text = city;
                [header0.B_attentionButton setTitle:[NSString stringWithFormat:@"%@ 关注", safeValue1(weSelf.userModel.followCount)] forState:UIControlStateNormal];
                [header0.B_fansButton setTitle:[NSString stringWithFormat:@"%@ 粉丝", safeValue1(weSelf.userModel.fansCount)] forState:UIControlStateNormal];
                [header0.B_footerPrintButton setTitle:[NSString stringWithFormat:@"%@ 足迹", safeValue1(weSelf.userModel.trackCount)] forState:UIControlStateNormal];
                [header0.B_userImageView sd_setImageWithURL:[NSURL URLWithString:weSelf.userModel.portrait]];
                /// 设置用户的类型标签
                [header0.B_userStatusImageView setUsetType:weSelf.userModel.userType];
                header0.mineHeaderAction = ^(NSString *string) {
                    HXLog(@"string is -> %@", string);
                    if ([string isEqualToString:@"tx"]) {
                        //TODO:查看大图
                        
                        
                    } else if ([string isEqualToString:@"qd"]) {
                        //TODO:签到
                        [weSelf signData];
                    } else if ([string isEqualToString:@"jf"]) {
                        //TODO:积分
                        B_IntegralViewController * integral = [[B_IntegralViewController alloc] init];
                        [weSelf pushNextViewController:integral];
                    } else if ([string isEqualToString:@"sc"]) {
                        //TODO:收藏
                        B_CollectionViewController * colleciton = [[B_CollectionViewController alloc] init];
                        [weSelf pushNextViewController:colleciton];
                    } else if ([string isEqualToString:@"gz"]) {
                        //TODO:关注
                        B_AttentionViewController * attention = [[B_AttentionViewController alloc] init];
                        [weSelf pushNextViewController:attention];
                    } else if ([string isEqualToString:@"fs"]) {
                        //TODO:粉丝
                        B_FansViewController * fans = [[B_FansViewController alloc] init];
                        [weSelf pushNextViewController:fans];
                    } else if ([string isEqualToString:@"zj"]) {
                        //TODO:足迹
                        B_FooterPrintViewController * footer = [[B_FooterPrintViewController alloc] init];
                        [weSelf pushNextViewController:footer];
                    }
                };
                return header0;
            } else {
                B_MineHeaderMoreView * header1 = [B_MineHeaderMoreView initB_MineHeaderMoreView];
                NSArray * arr = @[@"我的话题", @"我的活动"];
                header1.B_titleLabel.text = arr[section - 1];
                header1.moreAction = ^{     //TODO:执行点击事件
                    if (section == 1) {
                        B_MyTopicListVC * myTopic = [[B_MyTopicListVC alloc] init];
                        [weSelf pushNextViewController:myTopic];
                    } else if (section == 2) {
                        B_MyActivityListVC * myActivity = [[B_MyActivityListVC alloc] init];
                        [weSelf pushNextViewController:myActivity];
                    }
                };
                return header1;
            }
            return nil;
        };
        /// 组尾的高度
        _mainView.heightForFooterBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                CGFloat height = (SCREEN_WIDTH - 4) /4.;
                if (weSelf.userModel.userPictureList.count % 4 == 0) {
                    return height * (weSelf.userModel.userPictureList.count / 4);
                } else {
                    return height * (weSelf.userModel.userPictureList.count / 4 + 1);
                }
                
            } else {
                return 0.1;
            }
        };
        /// 组尾
        _mainView.viewForFooterBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                B_MineFooterView * footer = [B_MineFooterView initB_MineFooterView];
                
                footer.imageArray = weSelf.imageArray;//weSelf.userModel.userPictureList;
                footer.collectionTapAction = ^(NSIndexPath *indexPath) {
                    //TODO:点击看大图的
                    HXLog(@"点击看大图");
                };
                return footer;
            } else {
                return nil;
            }
            return nil;
        };
        /// cell
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            if (indexPath.section == 0) {
                
            } else if (indexPath.section == 1) {
                B_MineTopicTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_MineTopicTVC" forIndexPath:indexPath];
                
                return cell;
            } else if (indexPath.section == 2) {
                B_MineActivityTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_MineActivityTVC" forIndexPath:indexPath];
                
                return cell;
            }
            UITableViewCell * cell = [[UITableViewCell alloc] init];
            return cell;
        };
        /// cell的高度
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            
            return 270;
        };
        
    }
    return _mainView;
}





- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.navigationController.viewControllers.count > 1) {
        
    } else {
        [self setLeftImageBarButtonItemWithFrame:CGRectZero image:@"" selectImage:@"" action:nil];
        [self setNavigationBarBackgroundWithImage:[UIImage getImageWithColor:[UIColor clearColor] alp:0]];
        [self setNavigationBarShadowImge:[UIImage getImageWithColor:[UIColor clearColor] alp:0]];
    }
    // 数据请求
    [self getData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _animation = NO;
}
- (void)pushNextViewController:(UIViewController *)controller {
    [super pushNextViewController:controller];
    _animation = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)getData {
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/user/selectUserInfo/%@", getUserId()] parameters:nil isCache:YES succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20010"]) {
            NSLog(@"data is %@", data);
            weSelf.userModel = [B_UserBasicModel mj_objectWithKeyValues:data[@"values"]];
            [weSelf.imageArray removeAllObjects];
            for (NSDictionary * dictionary in weSelf.userModel.userPictureList) {
                [weSelf.imageArray addObject:dictionary[@"picture"]];
            }
            [weSelf.mainView.tableView reloadData];
            [weSelf.dataSource removeAllObjects];
            weSelf.dataSource = nil;
            [weSelf.dataArray removeAllObjects];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}


- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        B_CellModel * model0 = [B_CellModel initB_CellModelWithTitle:@"实名认证" withControllers:NSStringFromClass(B_RealNameViewController.class)];
        B_CellModel * model1 = [B_CellModel initB_CellModelWithTitle:@"申请商家" withControllers:NSStringFromClass(B_ApplyBusinessVC.class)];
        B_CellModel * model2 = [B_CellModel initB_CellModelWithTitle:@"我的钱包" withControllers:NSStringFromClass(B_MyWalletViewController.class)];
        B_CellModel * model3 = [B_CellModel initB_CellModelWithTitle:@"我的订单" withControllers:NSStringFromClass(B_MerchantOrderVC.class)];
        B_CellModel * model4 = [B_CellModel initB_CellModelWithTitle:@"我的消息" withControllers:NSStringFromClass(B_MyMessageViewController.class)];
        B_CellModel * model5 = [B_CellModel initB_CellModelWithTitle:@"扫一扫/二维码" withControllers:NSStringFromClass(B_SweepViewController.class)];
        B_CellModel * model6 = [B_CellModel initB_CellModelWithTitle:@"设置" withControllers:NSStringFromClass(B_SettingViewController.class)];
        B_CellModel * model7 = [B_CellModel initB_CellModelWithTitle:@"商户管理" withControllers:NSStringFromClass(B_UserOrderManagerVC.class)];
        
        if ([self.userModel.userType isEqualToString:@"1"] || [self.userModel.userType isEqualToString:@"2"]){
            _dataSource = [NSMutableArray arrayWithObjects:model0, model1, model2, model3, model4, model5, model6, nil];
        } else if ([self.userModel.userType isEqualToString:@"3"]) {
             _dataSource = [NSMutableArray arrayWithObjects:model7, model2, model3, model4, model5, model6, nil];
        } else {
            return nil;
        }
    
       
    }
    return _dataSource;
}


/**
 TODO:签到
 */
- (void) signData {
    WeakSelf(weSelf, self);
    
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/userSign/userSign/%@", getUserId()] parameters:nil isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20005"]) {
            B_ImageAlertView * alert = [B_ImageAlertView initB_ImageAlertView];
            alert.B_titleLabel.text = @"签到成功";
            alert.buttonAction = ^{
                //TODO:查看积分
                B_IntegralViewController * integral = [[B_IntegralViewController alloc] init];
                [weSelf pushNextViewController:integral];
            };
            [alert show];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
    
    
    
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    [self dismissViewControllerAnimated:YES completion:nil];
//
//    B_SettingViewController * setting = [[B_SettingViewController alloc] init];
//    [self pushNextViewController:setting];
    
//    if (getUserId()) {
//
//    }
    
    
//    AddressPickerView * address = [[AddressPickerView alloc] initWithShowQu:YES];
//    [address show];
//    address.sureMessage = ^(NSString *provice, NSString *city, NSString *area) {
//        
//    };
    
//    XGDatePicker * pic = [[XGDatePicker alloc] initWithType:PGDatePickerModeDate];
//    [pic showWithController:self Date:^(NSString *date) {
//        
//    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
